package com.gonsin.gview.common.utils;

import com.gonsin.base.exceptions.MyException;
import com.gonsin.gview.common.auth.BaseResultCodes;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

@Configuration
public class KeyOnlyUtils implements InitializingBean {

    static {

        // TODO 查询数据库，查询当前最大的id

    }

    @Override
    public void afterPropertiesSet() throws Exception {
    }

    /**
     * 生成一个新的key
     * @return
     */
    public static String general(String beanName){
        int length = 32 - beanName.length() - 1;
        return beanName + "_" +  RandomStringUtils.random(length, true, true);
    }

    /**
     * 检测key是否为所需的参数
     */
    public static void verify(String key, String beanName) {
        if(!key.startsWith(beanName + "_")){
            throw new MyException(BaseResultCodes.KEY_ERROR.getValue(),
                    String.format("传递的key值【%s】错误，正确格式应该是以【%s】开头的值，" +
                            "key值一般是某个实体类的主键，每个实体类的主键一般都会以实体类的名字为前缀，请仔细查找请求的接口是否有传错参数的情况。", key, beanName));
        }
    }
}
